<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/7
 * Time: 15:55
 */
require_once __DIR__ . '/../http/ResponseResult.php';
include_once __DIR__ . '/UserService.php';
include_once __DIR__ . '/SessionService.php';
$db = require_once __DIR__ . '/DatabaseService.php';

if (checkLogin()) {
    header('location:/index.php');
    responseError(5000, '重复登录');
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    return;
}
$data = $_POST;

if (isset($data['access']) === false) {
    responseError(1000, '用户名不能为空');
}

if (isset($data['password']) === false) {
    responseError(1001, '密码不能为空');
}

if (isset($data['code']) === false) {
    responseError(1002, '验证码不能为空');
}

if (isset($_SESSION['code']) && strtoupper($data['code']) !== strtoupper($_SESSION['code'])) {
    unset($_SESSION['code']);
    responseError(1003, '验证码不正确');
}

$user = getUserData($db, $data['access']);
if (empty($user)) {
    responseError(1004, '用户不存在');
}

if (userCheckPassword($user, $data['password'])) {
    setUserLogin(getUserInfo($db, $user['id']));
    responseSuccess('登录成功');
} else {
    responseError(1005, '用户/密码错误');
}